package com.jyannis.redisdemo.service;

import com.jyannis.redisdemo.mapper.PostingMapper;
import com.jyannis.redisdemo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class LikesService {

    @Autowired
    PostingMapper postingMapper;

    @Autowired
    RedisUtil redisUtil;

    //redis中存储的key名称规则
    private static String LIKE_KEY(Integer id){
        return "redisdemo:likes:" + id;
    }

    //从redis里取出点赞数
    private Integer getLikesFromRedis(Integer id){
        Integer likes;
        try{
            //从redis中取出键为LIKE_KEY(Integer id)的值
            likes = (Integer)redisUtil.get(LIKE_KEY(id));
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return likes;
    }


    public int getLikes(Integer id){
        Integer likes = getLikesFromRedis(id);
        //如果redis里能取出一个非null值（说明redis有维护这个帖子的点赞数），就直接返回
        if(likes != null)return likes;

        //redis中没存点赞数的情况
        //先从mysql里把点赞数取出来
        likes = Optional.ofNullable(postingMapper.getLikesByPrimaryKey(id)).orElse(0);

        //存到redis里
        redisUtil.set(LIKE_KEY(id),likes);
        return likes;
    }

    public void likes(Integer id){
        Integer likes = getLikesFromRedis(id);
        //如果redis里能取出一个非null值（说明redis有维护这个帖子的点赞数），就直接在原基础上+1
        if(likes != null){
            redisUtil.set(LIKE_KEY(id),likes + 1);
        }else{
            //redis取不出，就从mysql取
            likes = Optional.ofNullable(postingMapper.getLikesByPrimaryKey(id)).orElse(0);
            //存到redis里
            redisUtil.set(LIKE_KEY(id),likes + 1);
        }
    }
}
